package com.lgb.controller;

import com.lgb.Service.AnnouncementService;
import com.lgb.Service.BlogService;
import com.lgb.Service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private AnnouncementService announcementService;

    //跳转到博客首页
    @GetMapping("/")
    public  String index(@PageableDefault(size = 5 , sort = {"updateTime"} ,direction = Sort.Direction.DESC)
                                     Pageable pageable, Model model){
        model.addAttribute("page" , blogService.listBlog(pageable));
        model.addAttribute("types", typeService.listTypeTop(6));
        model.addAttribute("announcement" , announcementService.getOnlyone());
        return "index";
    }

    //搜索
    @PostMapping("search")
    public String search(@PageableDefault(size = 5 , sort = {"updateTime"} ,direction = Sort.Direction.DESC)
                                 Pageable pageable, Model model , @RequestParam String query){
        model.addAttribute("page" , blogService.listBlog("%" + query + "%",pageable));
        model.addAttribute("query" ,query);
        return "search_blog";
    }

    //博客详情
    @GetMapping("/blog/{id}")
    public  String blog(@PathVariable Long id , Model model){
        model.addAttribute("blog" , blogService.getAndConvert(id));
        return "blog";
    }
}
